package com.chanjx.myspringwebflux.config;

import com.chanjx.myspringwebflux.entity.Message;
import com.chanjx.myspringwebflux.handler.ChatSocketHandler;
import com.chanjx.myspringwebflux.handler.MyWebSocketHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.reactive.HandlerMapping;
import org.springframework.web.reactive.handler.SimpleUrlHandlerMapping;
import org.springframework.web.reactive.socket.WebSocketHandler;
import org.springframework.web.reactive.socket.server.support.WebSocketHandlerAdapter;
import reactor.core.publisher.Flux;
import reactor.core.publisher.UnicastProcessor;

import java.util.HashMap;

/**
 * @author 陈俊雄
 * @date 2019/5/15
 **/
@Configuration
public class WebSocketConfig {

    @Autowired
    private MyWebSocketHandler myWebSocketHandler;

    @Autowired
    private ChatSocketHandler chatSocketHandler;

    @Bean
    public HandlerMapping handlerMapping() {
        final HashMap<String, WebSocketHandler> map = new HashMap<>();
        map.put("/hello", myWebSocketHandler);
        map.put("/chat", chatSocketHandler);
        final SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
        mapping.setUrlMap(map);
        mapping.setOrder(Ordered.HIGHEST_PRECEDENCE);
        return mapping;
    }

    @Bean
    public WebSocketHandlerAdapter webSocketHandlerAdapter() {
        return new WebSocketHandlerAdapter();
    }

    @Bean
    public UnicastProcessor<Message> messageProcessor(){
        return UnicastProcessor.create();
    }

    @Bean
    public Flux<Message> messages(UnicastProcessor<Message> messagePublisher) {
        return messagePublisher
                .replay(2)
                .autoConnect();
    }
}
